from django.shortcuts import render,HttpResponse
from dwebsocket.decorators import accept_websocket,require_websocket
import time
import json
from showlog import settings

import subprocess
from db import models
from  showlog import settings
import os

# Create your views here.


@accept_websocket
def taillog(request):

    if not request.is_websocket():  # 判断是不是websocket连接
        return HttpResponse("123")
    else:
            id = request.GET.get("id")
            log_info = models.host_db.objects.filter(id=id).values()[0]
            # print("=======================")
            # print(log_info)
            log_path = log_info["host_log_path"]
            log_name = log_path.split('/')[-1]
            host_ip = log_info["host_ip"]
            host_user = log_info["host_user"]
            host_password = log_info["host_password"]
            # print(host_ip)
            print('收到websocket请求')
            static_path = settings.STATICFILES_DIRS

            while True:
                #同步文件
                result = subprocess.Popen('sshpass -p %s rsync -avz %s@%s:%s %s/%s-1' %(host_password,host_user,host_ip,log_path,static_path[0],log_name), stderr=subprocess.PIPE,stdout=subprocess.PIPE, shell=True)
                if result.stderr.read():
                    break
                #subprocess.Popen('sshpass -p xiyou123 rsync -avz root@%s:%s %s/%s-2' %(host_ip,log_path,static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                #生成两个文件,1个文件记录初始值,1个文件同步更新

                if os.path.exists("%s/%s-2" %(static_path[0],log_name)):

                    p = subprocess.Popen('cat %s/%s-2 | wc -l' %(static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                    init_number = int(p.stdout.read().decode("utf8"))
                else:
                    init_number = 0

                p1 = subprocess.Popen('cat %s/%s-1| wc -l' %(static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                file_number = int(p1.stdout.read().decode("utf8"))
                if init_number == 0:
                    request.websocket.send("x1")
                elif file_number <= 10 and file_number > init_number:
                    p2 = subprocess.Popen('cat %s/%s-1' %(static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                    for i in p2.stdout.readlines():
                        request.websocket.send(i)
                elif file_number > 10 and file_number > init_number:
                    new_number =  file_number - init_number
                    p2 = subprocess.Popen('tail -n %s %s/%s-1' %(new_number,static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                    for i in p2.stdout.readlines():
                        request.websocket.send(i)
                elif file_number == init_number:
                    request.websocket.send("xx")
                else:
                    request.websocket.send("x1")
                subprocess.Popen('rsync -avz %s/%s-1 %s/%s-2' %(static_path[0],log_name,static_path[0],log_name), stdout=subprocess.PIPE, shell=True)
                result.kill()
                time.sleep(5)

def showlog(request):
    id = request.GET.get("id")
    return render(request,"taillog.html",{"id":id})
def logdown(request):
    id = request.GET.get("id")
    log_info = models.host_db.objects.filter(id=id).values()[0]
    log_path = log_info["host_log_path"]
    log_name = log_path.split('/')[-1]
    host_ip = log_info["host_ip"]
    host_user = log_info["host_user"]
    host_password = log_info["host_password"]
    static_path = settings.STATICFILES_DIRS
    result = subprocess.Popen('sshpass -p %s rsync -avz %s@%s:%s %s/%s' % (
    host_password, host_user, host_ip, log_path, static_path[0], log_name), stderr=subprocess.PIPE,
                              stdout=subprocess.PIPE, shell=True)
    host_list = models.host_db.objects.values()
    info = {}
    info = {"host_list": host_list}
    if result.stderr.read():
        info = {"result":"null"}
    else:
        down_path = "%s" %(log_name)
        info["result"] = down_path
    return render(request,"hostlist.html",info)

def cmdlog(request):
    pass